package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.User;
import com.jt.service.DubboUserService;
import com.jt.service.UserService;
import com.jt.util.CookieUtil;
import com.jt.vo.SysResult;
import com.zaxxer.hikari.util.FastList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisCluster;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/user")
public class UserController {

    @Reference(check = false)
    private DubboUserService dubboUserService;

    @Reference
    private UserService userService;

    @Autowired
    private JedisCluster jedisCluster;

    @RequestMapping("/{moduleName}")
    public String module(@PathVariable String moduleName){
        return moduleName;
    }

    @RequestMapping("/doRegister")
    @ResponseBody
    public SysResult saveUser(User user){
        //利用dubbo进行RPC调用
        dubboUserService.saveUser(user);
        return SysResult.success();
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public SysResult doLogin(User user, HttpServletResponse response){
        String ticket= userService.doLogin(user);
        if(StringUtils.isEmpty(ticket)){
            //说明用户名或者密码错误
            return SysResult.fail();
        }else{
            //1.创建Cookie
            Cookie cookie = new Cookie("JT_TICKET",ticket);
            cookie.setMaxAge(7*24*60*60);   //设定cookie存活有效期
            cookie.setPath("/");            //设定cookie有效范围
            cookie.setDomain("jt.com");     //设定cookie共享的域名 是实现单点登录必备要素
            response.addCookie(cookie);
            return SysResult.success();     //表示用户登录成功!!
        }
    }



    @RequestMapping("logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){
        //1.根据JT_TICKET获取指定的ticket
        String ticket = CookieUtil.getCookieValue(request,"JT_TICKET");

        //2.判断ticket是否为null
        if(!StringUtils.isEmpty(ticket)){
            jedisCluster.del(ticket);
            CookieUtil.deleteCookie(response,"JT_TICKET","jt.com");
        }

        return "redirect:/";
    }
}
